package com.wxzhou.wangzhuan.api;

import com.wxzhou.wangzhuan.dto.*;
import com.wxzhou.wangzhuan.exception.UserBindException;
import com.wxzhou.wangzhuan.exception.WithdrawException;
import com.wxzhou.wangzhuan.security.UserContext;
import com.wxzhou.wangzhuan.service.AuthService;
import com.wxzhou.wangzhuan.util.AdvancedGsonPrettyPrint;
import io.smallrye.mutiny.Uni;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;

import java.util.Map;

/**
 * 子账号绑定、查询等接口
 */
@Path("/api")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BindApi {

    private static final Logger LOG = Logger.getLogger(BindApi.class);

    @Inject
    UserContext userContext;

    @Inject
    AuthService authService;

    /**
     * 主账号发送发送绑定请求，绑定某个子账号
     *
     * @param bindRequestDto
     * @return
     */
    @POST
    @Path("/bind")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> bind(@Valid BindRequestDto bindRequestDto) {
        boolean authenticated = userContext.isAuthenticated();
        if (!authenticated) {
            ResponseDto<Object> unauthorized = ResponseDto.unauthorized("");
            return Uni.createFrom().item(Response.status(unauthorized.getCode()).entity(unauthorized).build());
        }
        LOG.infof("设备绑定参数:%s", AdvancedGsonPrettyPrint.prettyPrint(bindRequestDto));
        return authService.bindSubUser(bindRequestDto, userContext.getCurrentUserInfo().get())
                .onItem().transform(response -> {
                    ResponseDto success = ResponseDto.success();
                    return Response.ok(success).build();
                })
                .onFailure().recoverWithUni(throwable -> {
                    String msg = "";
                    if (throwable instanceof UserBindException) {
                        msg = throwable.getMessage();
                    }
                    ResponseDto<Map<String, Object>> resp = ResponseDto.error(msg);
                    return Uni.createFrom().item(Response.status(500).entity(resp).build());
                });

    }

    /**
     * 查询用户的子账号绑定记录
     *
     * @param bindRecordRequestDto
     * @return
     */
    @POST
    @Path("/bind-record")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> findBindRecord(@Valid BindRecordRequestDto bindRecordRequestDto) {
        boolean authenticated = userContext.isAuthenticated();
        if (!authenticated) {
            ResponseDto<Object> unauthorized = ResponseDto.unauthorized("");
            return Uni.createFrom().item(Response.status(unauthorized.getCode()).entity(unauthorized).build());
        }
        return authService.getPageList(bindRecordRequestDto, userContext.getCurrentUserInfo().get())
                .onItem().transform(response -> {
                    if (response != null) {
                        ResponseDto<PageResponseDto<BindRecordResponseDto>> success = ResponseDto.success(response);
                        return Response.ok(success).build();
                    } else {
                        ResponseDto<Map<String, Object>> resp = ResponseDto.fail("查询失败");
                        return Response.status(500).entity(resp).build();
                    }
                })
                .onFailure().recoverWithUni(throwable -> {
                    String msg = "";
                    if (throwable instanceof UserBindException) {
                        msg = throwable.getMessage();
                    }
                    ResponseDto<Map<String, Object>> resp = ResponseDto.error("查询失败" + msg);
                    return Uni.createFrom().item(Response.status(500).entity(resp).build());
                });
    }

    /**
     * 查询用户的子账号绑定面板
     *
     * @param bindRecordRequestDto
     * @return
     */
    @POST
    @Path("/bind-dashboard")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> findBindRecordDashboard(@Valid CommonRequestDto bindRecordRequestDto) {
        boolean authenticated = userContext.isAuthenticated();
        if (!authenticated) {
            ResponseDto<Object> unauthorized = ResponseDto.unauthorized("");
            return Uni.createFrom().item(Response.status(unauthorized.getCode()).entity(unauthorized).build());
        }
        return authService.getBindDashboard(userContext.getCurrentUserInfo().get())
                .onItem().transform(response -> {
                    ResponseDto success = ResponseDto.success(response);
                    return Response.ok(success).build();
                })
                .onFailure().recoverWithUni(throwable -> {
                    String msg = "";
                    if (throwable instanceof WithdrawException) {
                        msg = throwable.getMessage();
                    }
                    ResponseDto<Map<String, Object>> resp = ResponseDto.error("查询面板数据失败" + msg);
                    return Uni.createFrom().item(Response.status(500).entity(resp).build());
                });
    }


}
